<?php
namespace app\common\model;
use think\Db;
/**
 * 分类模型
 */
class ServiceCat extends Base {
	/**
	 * 列表
	 */
	public function listQuery($parentId = 0){
		$parentId = $parentId ? $parentId : input('parentId',0);
		$where[] = ['dataFlag','=',1];
		$where[] = ['parentId','=',$parentId];
		$rs = $this->where($where)
			->order('dataSort desc,catId asc')
			->select();
		return $rs;
	}
	/**
	 * 获取分类名称
	 */
	public function getCatTitles($catIdPath){
		if($catIdPath == '')return '';
		$catIds = str_replace("_",",",substr($catIdPath, 0, -1));
		$rs = $this->where("dataFlag=1 and catId in(".$catIds.")")->column('catTitle');
		if(!empty($rs)){
			return implode('→',$rs);
		}
	}
	/**
	 * 面包屑导航
	 * 迭代获取上级
	 * 返回上级数组
	 * php中实现数组反转array_reverse($catTitles);
	 *
	 * 用法
	 * $catTitles = array();
	 * $m = new ArticleCat();
	 * $catTitles = $m->getParents($catTitles,$catId);
	 */
	public function getParents($catTitles = array(),$catId){
		$rs = $this->field("catId,catTitle,parentId")->where("dataFlag=1 and catId=".$catId)->find();
		// dump($rs);
		if(!empty($rs)){
			$catTitles[] = $rs;
			if($rs['parentId']>0){
				return $this->getParents($catTitles,$rs['parentId']);               
			}else{
				return $catTitles;
			}
		}else{
			return $catTitles;
		}
	}
	/**
	 * 根据子分类获取其父级分类-添加商品，调用商品属性和商品规格时会用到getSpecAndAttr，商品添加修改都要用到
	 */
	public function getParentCatIds($id,$data = array()){
		$data[] = $id;
		$parentId = $this->where('catId',$id)->value('parentId');
		if($parentId==0){
			krsort($data);
			return $data;
		}else{
			return $this->getParentCatIds($parentId, $data);
		}
	}
	/**
	 * 根据子分类获取其一级分类id，，以便获取对应轮播图
	 */
	public function getParentCatId($id){
		$parentId = $this->where('catId',$id)->value('parentId');
		if($parentId==0){
			return $id;
		}else{
			return $this->getParentCatId($parentId);
		}
	}
	/**
	 * 商品分类路径-网页title用
	 */
	public function getParentTitles($catId){
		if($catId<=0)return [];
		$catIds = $this->getParentCatIds($catId);
		$rs = $this->where([['catId','in',$catIds]])->field('catTitle')->order('catId desc')->select();
		$names = [];
		foreach($rs as $v){
				$names[] = $v['catTitle'];
		}
		return $names;
	}
}